<template>
  <div class="top" :style="{opacity:opacity}">
    <div>
      <div 
        @click="isRotate = !isRotate" 
        :class=" isRotate? 'rotate menu' :'menu'" 
      >
        <i class="iconfont  icon-viewlist"></i>
      </div>
      <div class="logo">
        K.B
      </div>
    </div>
    
    <div class="user">
      <router-link to="/login">
        <p v-if="!isLogin" class="c000">登录/注册</p>
      </router-link>
      <p v-if="isLogin" class="c000">
        {{userName}}
        <i @click="close" class="iconfont close icon-wrong"></i>
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name:'Top',
  data() {
    return {
      opacity:0,
      isRotate:false,
      isLogin:false,
      userName:'',
    }
  },
  mounted(){
    this.getName()
    this.opacity = 0;
    this.showTop(this.$route.meta.isContent);
    this.$bus.$on('add',this.add);
    this.$bus.$on('remove',this.remove);
  },
  methods:{
    close(){
      localStorage.removeItem('login')
      this.$router.push('/login')
    },
    getName(){
      var userName = JSON.parse(localStorage.getItem('login'))
      if(userName){
        this.isLogin = true
        this.userName = userName.name
        this.$store.commit('setName',userName.name)
      }else{
        this.isLogin = false
      }
    },
    handleScroll(){
      var scrollTop = window.scrollY
      this.opacity = scrollTop/300
      if(this.opacity >= 1){
        this.opacity = 1
      }
    },
    showTop(isContent){
      if(isContent){
        this.opacity = 1
      }else{
        this.add()
      }
    },
    add(){
      window.addEventListener('scroll' ,this.handleScroll)
    },
    remove(){
      window.removeEventListener('scroll' ,this.handleScroll)
      this.opacity = 1
    },
  },
  watch: {
    '$route' (to ,from) {
      if(from.path=='/login'){
        this.getName()
      }
    }
  },
}
</script>

<style scoped>
 .top{
    width: 100%;
    height: 50px;
    background-color: #101010;
    padding: 10px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    position: fixed;
    top: 0;
    z-index: 10;
  }
  .top  .iconfont{
    color: white;
    font-size: 30px;
  }
  .menu{
    display: inline-block;
    transition: 0.6s;
    cursor: pointer;
    float: left;
  }
  .rotate{
    transform: rotate(90deg) !important;
  }
  .logo{
    text-align: center;
    font-family: fantasy;
    font-size: 30px;
    margin:0 20px;
    float: left;
  }
  .c000{
    color: hsla(0,0%,100%,.9);
    cursor: pointer;
  }
  .close{
    margin-left: 10px;
    font-size: 18px !important;
    color: gray !important;
  }
</style>